#!/bin/bash
#set -e

# Determine the FastDFS Model based on the incoming parameters(tracker or storage)
if [ "$1" = "storage" ] ; then
	FASTDFS_MODE="storage"
else 
  FASTDFS_MODE="tracker"
fi

# set tracker_server in storage.conf
if [ "$1" = "storage" ] ; then
 	if [ -n "$TRACKER_SERVER" ] ; then
 		sed -i "s|tracker_server=.*$|tracker_server=${TRACKER_SERVER}|g" /etc/fdfs/storage.conf
 		sed -i "s|tracker_server=.*$|tracker_server=${TRACKER_SERVER}|g" /etc/fdfs/mod_fastdfs.conf
 		if [ -n "$NGINX_PORT" ]; then
 			sed -i "s|http.server_port=.*$|http.server_port=${NGINX_PORT}|g" /etc/fdfs/storage.conf
 			sed -i "s|listen        8888;$|listen        ${NGINX_PORT};|g" /etc/fdfs/nginx.conf
 		fi
 		# start nginx
 		yes | cp /etc/fdfs/nginx.conf /opt/nginx/conf/
		/opt/nginx/sbin/nginx
 	else
 		# no tracker_server exit
 		echo "Storage Must Has TRACKER_SERVER"
 		exit 0
 	fi
fi 

# log
FASTDFS_LOG_FILE="${FASTDFS_PATH}/logs/${FASTDFS_MODE}d.log"
# pid
PID_NUMBER="${FASTDFS_PATH}/data/fdfs_${FASTDFS_MODE}d.pid"

# start
/etc/init.d/fdfs_${FASTDFS_MODE}d start

# wait 10s
TIMES=10
while [ ! -f "$PID_NUMBER" -a $TIMES -gt 0 ]
do
    sleep 1s
	TIMES=`expr $TIMES - 1`
done

# write log in order to not exit
tail -f "$FASTDFS_LOG_FILE"
